/**
 * @Description: http详解 || Node使用express框架开发web基础入门
 * @DescriptionLink: https://segmentfault.com/a/1190000022402271
 * @DescriptionLink:  https://www.bilibili.com/video/BV1EZ4y1H7br?p=3
 * @author 麦田守望客
 * @date 2020/8/12
 **/
//主文件app.js 主服务器文件 应该只干一件事就是拦截所有请求
const http=require('http');
const fs=require('fs');
const hostname="127.0.0.1";
const port=8003;
const server=http.createServer();
server.on('request',(request,response)=>{ //拦截
  console.log('请求路径url:'+request.url)
  let url=request.url;// /index.html
  let newUrl=url.split('.'); //拆分字符串得到数组
  console.log(newUrl); //[ '/day01', 'html' ]
  if (newUrl[1]=='html'){ //根据不同的情况响应给页面的东西,就应该放在controller
    fs.readFile(`../src/page${newUrl[0]}.html`,"utf-8",function (err,data) {
      console.log("响应html内容:"+data)
      response.writeHead(200,{"content-type":"text/html;charset=utf-8"})
      response.write(data)
      response.end()
    })
  }else if(newUrl[1]=='css'){
    fs.readFile(`../src${newUrl[0]}.css`,"utf-8",function (err,data) {
      response.writeHead(200,{"content-type":"text/css;charset=utf-8"})
      response.write(data)
      response.end()
    })
  }else if(newUrl[1]=='js'){
    fs.readFile(`../src${newUrl[0]}.js`,"utf-8",function (err,data) {
      response.writeHead(200,{"content-type":"text/javascript;charset=utf-8"})
      response.write(data)
      response.end()
    })
  }else if(newUrl[1]=='jpg'||newUrl[1]=='png'||newUrl[1]=='gif'||newUrl[1]=='jpeg'||newUrl[1]=='jfif'){
    fs.readFile(`../src${newUrl[0]}.${newUrl[1]}`,function (err,data) {
      response.writeHead(200,{"content-type":`image/${newUrl[1]}`})
      response.write(data)
      response.end()
    })
  }
})
server.listen(port,hostname,()=>{
  console.log(`服务器启动成功,可以通过 http://${hostname}:${port} 来访问`);
})

// 请求过来的拦截顺序是什么样的?
// 先是从app进来然后到router根据请求分发任务到controller(调用里的方法到dao)
// app=>router=>controller=>dao[middleware]
// 数据持久到数据库(在这里对数据库进行操作)=>model